<?php

class ProductsController extends Controller
{
  public $layout='//layouts/admin';

  public function filters()
  {
    return array(
      'accessControl',
    );
  }

  public function accessRules()
  {
    return array(
      array('allow',
        'actions'=>array('index','view'),
        'users'=>array('*'),
      ),
      array('allow',
        'actions'=>array('create','update','list','delete','updateStatus','updateFeature','upDisplay','downDisplay'),
        'users'=>array('@'),
      ),
      array('deny',  // deny all users
        'users'=>array('*'),
      ),
    );
  }

  public function actionIndex($data=null)
	{
		if ($data==null) {
			 $this->redirect(array('productCategories/index'));	
		}
		
	 $this->layout = '//layouts/main';	
			$productCategoriesList = ProductCategories::model()->with('products','subProductCategories')->findAll(array(
      		'condition'=>'t.enable=:enable AND t.main_product_category_id is null',
      		'params'=>array(':enable' => true),
      	));
      
    	$productCategoryModel =  ProductCategories::model()->find(array(
      		'condition'=>'enable=:enable AND slug=:slug',
      		'params'=>array(':enable' => true, ':slug' => $data),
      	));  
    	
    	$modelsList = Products::model()->findAll(array(
      		'condition'=>'enable=:enable AND product_category_id=:product_category_id',
      		'params'=>array(':enable' => true, ':product_category_id' => $productCategoryModel->id),
      	));     	

		$this->render('index',array(
			'modelsList'=>$modelsList,
			'productCategoryModel' => $productCategoryModel,
			'productCategoriesList' => $productCategoriesList
		));
	}

  public function actionView($data)
  {
    $this->layout = '//layouts/main';

    $model = Products::model()->find(array(
      'condition'=>'enable=:enable AND slug=:slug',
      'params'=>array(':enable' => true, ':slug' => $data),
    ));
    
		if ($model==null) {
			 $this->redirect(array('site/index'));	
		}    

			$productCategoriesList = ProductCategories::model()->with('products','subProductCategories')->findAll(array(
      		'condition'=>'t.enable=:enable AND t.main_product_category_id is null',
      		'params'=>array(':enable' => true),
      	));		
		
    $productPhotosList = ProductPhotos::model()->findAll(array(
      'condition'=>'product_id=:product_id AND enable=:enable',
      'params'=>array(':product_id'=>$model->id, ':enable' => true),
      'order'=>'display_order'
    ));

    $galleriesList = array();
    foreach ($productPhotosList as $data) {
      $galleriesList[] = array(
        'image_path' => Yii::app()->request->getBaseUrl(true).$data->photo_path,
        'thumbnail_path' => Yii::app()->request->getBaseUrl(true).$data->thumbnailPath,
        'description' => $data->description
      );
    }

    $this->metaKeyword = $model->name_en. ' : '.$this->metaKeyword;
    $this->metaDescription = strip_tags($model->description);

    $orderModel = new Orders;

    if(isset($_POST['Orders']))
    {
    	$orderModel->scenario = 'create';
      $orderModel->attributes=$_POST['Orders'];
      if($orderModel->save()) {
        $headers="From: {$orderModel->email}\r\nReply-To: {$orderModel->email}";
        $headers .= 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        $body = "Name: ".$orderModel->name ."<br />";
        $body .= $orderModel->message;
        mail(getConfig('email_sale'),'[Order] From :'.$orderModel->name,$body,$headers);
        Yii::app()->user->setFlash('order','Thank you for your message. We will respond to you as soon as possible.');
        $this->refresh();
        $orderModel = new Orders;
      }
    }    

    $this->render('view',compact('model', 'productCategoriesList', 'galleriesList', 'orderModel'));
  }

  public function actionCreate($productCategoryId=null)
  {
    $model=new Products;
    if($productCategoryId!=null) {
    	$model->product_category_id = $productCategoryId;
    }
    $productCategoryModel = ProductCategories::model()->findByPk($productCategoryId);

    if(isset($_POST['Products']))
    {
      $model->attributes=$_POST['Products'];
      if($model->save()) {
        $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));
      }
    }

    $this->render('create',array(
      'model'=>$model,
      'productCategoryModel' => $productCategoryModel
    ));
  }

  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);
    
    $productCategoryModel = ProductCategories::model()->findByPk($model->product_category_id);

    if(isset($_POST['Products']))
    {
      $model->attributes=$_POST['Products'];
      if($model->save())
        $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));
    }

    $this->render('update',array(
      'model'=>$model,
      'productCategoryModel' => $productCategoryModel
    ));
  }

  public function actionUpDisplay($id)
  {
      $model = $this->loadModel($id);
      $display_order = $model->display_order-1;
      $prev_model = Products::model()->find(array(
        'condition'=>'display_order=:display_order',
        'params'=>array(':display_order' => $display_order),
      ));
      $prev_model->display_order = $prev_model->display_order+1;

      $model->display_order = $display_order;
      $prev_model->save();
      $model->save();
      $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));
  }

  public function actionDownDisplay($id)
  {
      $model = $this->loadModel($id);
      $display_order = $model->display_order+1;

      $max_display_order = $model->getMaxDisplayOrder();

      $next_model = Products::model()->find(array(
        'condition'=>'display_order=:display_order',
        'params'=>array(':display_order' => $display_order),
      ));
      if ($model->display_order < $max_display_order) {
        $next_model->display_order = $next_model->display_order-1;

        $model->display_order = $display_order;
        $next_model->save();
        $model->save();
      }
      $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));

  }

  public function actionDelete($id)
  {
    if(Yii::app()->request->isPostRequest)
    {
      $model = $this->loadModel($id);

      Products::model()->updateCounters(
        array('display_order'=> -1),
        'display_order >:display_order',
        array(':display_order' => $model->display_order)
      );

      $model->active_flag = 0;
      $model->enable= 0;
      $model->display_order = 0;
      $model->save();

      if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
  }

  public function actionList($productCategoryId = null)
  {
  	if ($productCategoryId==null) {
  		$this->redirect(array('productCategories/list'));
  	}
  	
  	$productCategoryModel = ProductCategories::model()->findByPk($productCategoryId);
  	
    $dataProvider=new CActiveDataProvider('Products',
      array (
       'criteria' => array(
       	 'condition' => 'active_flag=true AND product_category_id=:product_category_id',
       	 'params' => array(':product_category_id' => $productCategoryId),
         'order'=>'display_order ASC'
       )
      )
    );
    
    $this->render('list',array(
      'dataProvider'=>$dataProvider,
      'productCategoryModel' => $productCategoryModel
    ));
  }

  public function actionUpdateStatus($id)
  {
    $model = $this->loadModel($id);

    $model->enable = ($model->enable==true) ? 0 : 1;
    $model->save();
    $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));

  }
  
  public function actionUpdateFeature($id)
  {
    $model = $this->loadModel($id);

    $model->feature = ($model->feature==true) ? 0 : 1;
    $model->save();
    $this->redirect(array('list', 'productCategoryId' => $model->product_category_id));

  }  

  public function loadModel($id)
  {
    $model=Products::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='products-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
